<template>
  <div class="va-df-input-counter" :disabled="field.disabled">
    <div class="va-df-input-counter-left" @click="sub" @mousedown.stop.prevent="focus" :class="{disabled: counter - step < validMin}">-</div>
    <input ref="inputInstance" type="text" :value="counter" @input="onChange" :disabled="field.disabled" @keyup.up.stop.prevent="plus" @keyup.down.stop.prevent="sub">
    <div class="va-df-input-counter-right" @click="plus" @mousedown.stop.prevent="focus" :class="{disabled: counter + step > validMax}">+</div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import _ from 'lodash'

  /*
  * field配置
  *   max
  *   min
  *   disabled
  * */
  export default {
    props: {
      field: {
        type: Object,
        default () {
          return {}
        }
      },
      disabled: Boolean,
      value: {
        default: 0
      }
    },
    mounted () {
      Vue.nextTick(() => {
        if (this.value < this.validMin) {
          this.counter = this.validMin
        } else if (this.value > this.validMax) {
          this.counter = this.validMax
        } else {
          if (this.counter !== this.value) {
            this.counter = this.value
          }
        }
      })
    },
    computed: {
      validMin () {
        let min = +this.field.min
        if (_.isNil(this.field.min) || _.isNaN(min)) {
          min = Number.MIN_VALUE
        }
        return min
      },
      validMax () {
        let max = +this.field.max
        if (_.isNil(this.field.max) || _.isNaN(max)) {
          max = Number.MAX_VALUE
        }
        return max
      },
      step () {
        return +this.field.step || 1
      },
      counter: {
        get () {
          let v = Math.ceil(+this.value)
          if (_.isNaN(v)) {
            return 0
          }
          return v
        },
        set (v) {
          v = +v
          if (_.isNaN(v)) {
            v = 0
          }
          v = Math.ceil(v)
          this.$emit('input', v)
        }
      }
    },
    methods: {
      onChange (e) {
        this.setVal(+e.target.value)
        if (e.target.value !== this.counter + '') {
          e.target.value = this.counter
        }
      },
      setVal (v) {
        if (_.isNaN(v) || v < this.validMin || v > this.validMax) {
          v = this.counter
        } else {
          v = Math.ceil(v)
        }
        this.counter = v
      },
      plus () {
        if (this.disabled) return
        this.setVal(this.counter + this.step)
      },
      sub () {
        if (this.disabled) return
        if (this.counter > 0) {
          this.setVal(this.counter - this.step)
        }
      },
      focus () {
        if (this.disabled) return
        this.$refs.inputInstance.focus()
      }
    }
  }
</script>
